/* Copyright 2007 Gearbox Software - http://www.gearboxsoft.com
 
 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at
 
     http:www.apache.org/licenses/LICENSE-2.0
 
 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.*/
namespace GearBlog.Web.Utils
{
	using System.Collections.Specialized;
	using System.Text.RegularExpressions;
	using Castle.MonoRail.Framework;

	public static class UrlUtil
    {

        public static OrderedDictionary ParseUrl(string url)
        {
            const string UrlParseExpression = @"(?<protocol>\w+)://((?<user>[\w]+):?(?<password>\w+)?[@])?(?<hostname>\w+)(:?(?<portNumber>\d+))?(?<appPath>[/\w+.]*)?(\?(?<queryString>[\w+.&=%]*))?";
            
            Regex regex = new Regex(UrlParseExpression);
            Match match = regex.Match(url);

            OrderedDictionary resultDictionary = new OrderedDictionary();
            string[] groupNames = regex.GetGroupNames();
            foreach (string groupName in groupNames)
            {
                int temp;
                if (!int.TryParse(groupName, out temp))
                    resultDictionary.Add(groupName, match.Groups[groupName].Value);
            }

            return resultDictionary;
        }
        public static string GetFullPath(Controller controller, string relativeUrl)
        {
            Regex appPathRemoveSlash = new Regex(@"(?<value>([\w:/.])+[^/])[/]*$");
            Regex relativeUrlRemoveSplash = new Regex(@"/*(?<value>\S+)");
            return appPathRemoveSlash.Match(controller.Context.ApplicationPath).Groups["value"].Value + '/' +
                relativeUrlRemoveSplash.Match(relativeUrl).Groups["value"].Value;
        }
    }
}